use axum::{http::StatusCode, routing::get_service, Router};
use tower_http::{
    cors::{Any, CorsLayer},
    services::ServeDir,
};

// Learn more about Tauri commands at https://tauri.app/develop/calling-rust/
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    let cors = CorsLayer::new()
        .allow_origin(Any)
        .allow_headers(Any)
        .allow_methods(Any);
    let mod_router = Router::new().nest_service(
        "/mod",
        get_service(ServeDir::new("mod"))
            .handle_error(|_err| async move { (StatusCode::INTERNAL_SERVER_ERROR, "加载mod失败!") })
            .layer(cors),
    );

    tauri::Builder::default()
        .plugin(tauri_plugin_store::Builder::new().build())
        .setup(|_app| {
            tokio::spawn(async move {
                let listener = tokio::net::TcpListener::bind("127.0.0.1:8085")
                    .await
                    .unwrap();
                axum::serve(listener, mod_router).await.unwrap();
            });
            Ok(())
        })
        .plugin(tauri_plugin_opener::init())
        .invoke_handler(tauri::generate_handler![greet])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
